package org.porridge.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.porridge.po.RecordSubmit;
import org.porridge.po.Resource;
import org.porridge.po.SeachLog;
import org.porridge.util.SVNManager;

/**
 * 
 * <p>Title: svnfindlog   </p>
 * <p>Description: 查询日志
 * 查询组合条件一    时间范围限制
 * 查询组合条件二    版本号限制
 * 查询组合条件三    多上传人过滤    如果有做限制上传人  在前后加;    ;admin;mast;  用indexOf(";admin;")  才能实现多用户判断
 * 查询组合条件四    目录限制</p>
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: svnkit</p>
 * <p>Create Date/Time: 2014年8月12日 下午8:24:59<p>
 * @author porridge
 * @version 1.0
 * @url www.prdblog.com
 *
 */
public class svnfindlog extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SVNManager svn=(SVNManager) request.getSession().getAttribute("svn");
		if(svn!=null){
			SeachLog seach=new SeachLog();// 填充搜索条件
			Field[] fies=seach.getClass().getDeclaredFields();
			Object obj=null;
			for(Field f:fies){
				f.setAccessible(true);
				obj=request.getParameter(f.getName());
				if(obj!=null && obj.toString().trim().length()>0)
					try {
						f.set(seach,obj.toString().trim());
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			
			try {
				if(seach.getUsername()!=null && seach.getUsername().trim().length()>0)
					seach.setUsername(";"+seach.getUsername()+";");
				
				List<Resource> resu=svn.filterCommitLog(seach);
				StringBuffer stb=new StringBuffer();
				for(Resource re:resu){
					stb.append("{\"svnversion\":\""+re.getSVNVersion()+"\",\"submituser\":\""+re.getSubmituser()+"\",\"submittime\":\""+re.getSubmittime()+"\",\"remark\":\""+rethtml(re.getRemark())+"\",files:[");
					if(re.getRes()!=null && re.getRes().size()>0){
						for(int i=0;i<re.getRes().size();i++){
							stb.append("{\"type\":\""+re.getRes().get(i).getType()+"\",\"path\":\""+re.getRes().get(i).getPath()+"\"}");
							if(i+1!=re.getRes().size())
								stb.append(",");
						}
					}
					stb.append("]},");
				}
				response.setCharacterEncoding("UTF-8");
				PrintWriter out=response.getWriter();
				if(stb.length()>0)
					out.print("["+stb.substring(0,stb.length()-1)+"]");
				else
					out.print("[]");
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	  private String rethtml(String html){
	    	if(html!=null){
				html=html.replaceAll("<","&lt;");
				html=html.replaceAll("\"","&quot;");
				html=html.replaceAll(">","&gt;");
				html=html.replaceAll("'","&#39;");
				html=html.replaceAll("\n","<br/>");
	    	}
			return html;
		}
}
